package net.gamebookengine.viewer.parser;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import net.gamebookengine.viewer.entities.Gamebook;

import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class InputParser {

	private Gamebook gamebook;
	private HashMap<String, Bitmap> images;

	public InputParser(InputStream input) {
		gamebook = new Gamebook();
		images = new HashMap<String, Bitmap>();
		inflateZip(input);
	}

	private void inflateZip(InputStream input) {
		ZipInputStream zipIn = new ZipInputStream(input);
		ZipEntry entry;
		try {
			entry = zipIn.getNextEntry();
			while (entry != null) {
				String fileName = entry.getName();
				if (fileName.equals("gamebook.xml")) {
					parseGamebook(zipIn);
				} else if (fileName.startsWith("media/")
						&& (fileName.endsWith(".gif")
								|| fileName.endsWith(".jpg") || fileName
									.endsWith(".png"))) {
					parseImages(fileName, zipIn);
				}
				entry = zipIn.getNextEntry();
			}
			zipIn.closeEntry();
			zipIn.close();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void parseImages(String fileName, ZipInputStream zipIn) {
		Bitmap bitmap = BitmapFactory.decodeStream(zipIn);
		images.put(fileName.substring(6), bitmap);
	}

	private void parseGamebook(ZipInputStream zipIn) throws Exception {
		Serializer serializer = new Persister();
		gamebook = serializer.read(Gamebook.class, zipIn);
	}

	public Gamebook getGamebook() {
		return gamebook;
	}

	public HashMap<String, Bitmap> getImages() {
		return images;
	}

}
